<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

<input type="file" name="file" multiple="multiple" />
<button onclick="uploadFile()" style="width: 120;height: 40;">提交</button>
<br /><br /><br />
<textarea id="content" style="width: 600px; height: 400px;"> </textarea>


</body>

<script>


    //普通get请求
    /* 		getRequest('json/data.json', {mode:'no-cors', // 这里需要设置一下
            }, function(data) {
                document.getElementById("content").innerText = JSON.stringify(data);
                console.log(data);
            }, function(error) {
                console.log(error);
            }); */

    getRequest('http://localhost:8080/list', {mode:'no-cors', // 这里需要设置一下
    }, function(data) {
        document.getElementById("content").innerText = JSON.stringify(data);
        console.log(data);
    }, function(error) {
        console.log(error);
    });

    //上传请求
    function uploadFile() {
        uploadFileRequest("file", {
            userName: '李四',
            age: 15
        }, 'http://localhost:8080/upload', {mode:'no-cors'},function(data){
            console.log("上传成功:");
            console.log(data);
        },function(error){
            console.log("上传失败");
        });

    }



    /**
     * 请求实现方法
     */
    function RequestData(url, initParams, successFunc = null, errorFunc = null) {

        var defaultInitParams = {
            //body: data,   // must match 'Content-Type' header
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include (发送带凭据的请求), same-origin, *omit
            /* headers: {
                'user-agent': 'Mozilla/4.0 MDN Example',
                'content-type': 'application/json'
            }, */
            method: 'GET', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, cors, *same-origin
            redirect: 'follow', // manual, *follow, error
            referrer: 'no-referrer', // *client, no-referrer
        };

        //如果请求方法为GET 和 HEAD 就去除body信息
        defaultInitParams.body = initParams.method != 'GET' && initParams.method != 'HEAD' ?
            defaultInitParams.body : null;

        initParams.body = initParams.method != 'GET' && initParams.method != 'HEAD' ?
            initParams.body : null;

        defaultInitParams = Object.assign(defaultInitParams, initParams);

        fetch(
            url, defaultInitParams
        )
            .then(function(response) {
                //先只处理响应状态正常的
                if(response.status===200){
                    return response.json();
                }
                return response;
            }).then(function(response) {

            //并没有返回信息
            if(response.body==null && response.status!=200){
                console.log("-----");
            }

            if (typeof(successFunc) == "function") {
                successFunc(response);
            }

        }).catch(function(error) {
            if (typeof(errorFunc) == "function") {
                errorFunc(error)
            }
        });

    }





    /**
     * get请求
     */
    function getRequest(url, initParams, successFunc = null, errorFunc = null) {
        initParams =initParams||{method: "GET",headers:{content-type:"application/x-www-form-urlencoded"}};
        RequestData(url, initParams, successFunc, errorFunc);
    }

    /**
     * post请求
     */
    function postRequest(url,data,initParams, successFunc = null, errorFunc = null) {
        initParams =initParams||{method: "POST",body:data};
        RequestData(url, initParams, successFunc, errorFunc);
    }


    /**
     * put请求
     */
    function putRequest(url, initParams, successFunc = null, errorFunc = null) {
        initParams =initParams||{method: "PUT",body:data};
        RequestData(url, initParams, successFunc, errorFunc);
    }

    /**
     * delete请求
     */
    function deleteRequest(url, initParams, successFunc = null, errorFunc = null) {
        initParams =initParams||{method: "DELETE",body:data};
        RequestData(url, initParams, successFunc, errorFunc);
    }

    /**
     * head请求
     */
    function headRequest(url, initParams, successFunc = null, errorFunc = null) {
        initParams =initParams||{method: "HEAD",body:data};
        RequestData(url, initParams, successFunc, errorFunc);
    }

    //上传文件 [支持多个文件上传]
    function uploadFileRequest(fileKey = "file", otherParams = {}, url, initParams, successFunc = null, errorFunc =
        null) {

        var formData = new FormData();
        var photos = document.querySelector("input[type='file'][multiple]");

        for (var param in otherParams) {
            formData.append(param, otherParams[param]);
        }

        // formData 只接受文件、Blob 或字符串，不能直接传递数组，所以必须循环嵌入
        for (let i = 0; i < photos.files.length; i++) {
            formData.append(fileKey, photos.files[i]);
        }

        initParams = initParams||{};
        initParams.body=formData;
        initParams.method=initParams.method||"POST";

        postRequest(url,initParams,successFunc,errorFunc);
    }
</script>
</html>
